/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package superchat;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;

/**
 * Classe de gestion de socket
 * @author georgesm
 */
public class Communication extends Thread {

    public Socket socket;
    public Object maitre;
    public DataInputStream in;
    public DataOutputStream out;
    public JSONObject message;

    /**
     * Constructeur
     * @param socket Socket de liaison
     * @param maitre Objet qui a créé la communication (client ou serveur)
     */
    public Communication(Socket socket, Object maitre) {
        try {
            this.socket = socket;
            this.maitre = maitre;

            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
        } catch (Exception ex) {
            Logger.getLogger(Communication.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Thread de récéption de messages
     */
    @Override
    public void run() {
        boolean run = true;
        while (run) {
            try {
                message = new JSONObject(in.readUTF());
                if (maitre instanceof Serveur) {
                    ((Serveur) maitre).interpretMessage(this);
                } else if (maitre instanceof SuperChatView) {
                    ((SuperChatView) maitre).interpretMessage(this);
                }
            } catch (Exception ex) {
                System.out.println("Erreur communication : communication atomisée");
                try {
                    socket.close();
                    if (maitre instanceof Serveur) {
                        ((Serveur) maitre).disconnect(this);
                    }
                    else if (maitre instanceof SuperChatView) {
                        ((SuperChatView) maitre).disconnect(this);
                    }
                } catch (Exception ex1) {
                    Logger.getLogger(Communication.class.getName()).log(Level.SEVERE, null, ex1);
                }
                run = false;
            }
        }
    }
}
